﻿using BaseDll;
using CommonTools;
using MotionIoLib;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace StationDemo
{
    public partial class Form_AxisTestSunny : UIPage, IUserRightSwitch
    {
        public Form_AxisTestSunny()
        {
            userRight = UserRight.Debug;
            InitializeComponent();
            ParamSetMgr.GetInstance().m_eventLoadProductFileUpadata += updatadataGridView;
            ParamSetMgr.GetInstance().m_eventSaveParam += ParamSave;

            ButtonColor(Btn_TestStop, Color.Red);
        }

        public UserRight userRight
        {
            set;
            get;
        }

        private void SaveMotorParam_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(ParamSetMgr.GetInstance().CurrentWorkDir + ("\\") + ParamSetMgr.GetInstance().CurrentProductFile)
               || ParamSetMgr.GetInstance().CurrentProductFile == null || ParamSetMgr.GetInstance().CurrentProductFile == "")
            {
                UIMessageBox.ShowError("当前产品文件夹不存在，请创建载入或者创建当前产品");
                return;
            }
            TMovePrm prm = new TMovePrm();
            THomePrm homePrm = new THomePrm();
            int indexCell = 0;
            for (int index = 0; index < dataGridView_AxisParamSet.RowCount; index++)
            {
                int nAxisNo = Convert.ToInt32(dataGridView_AxisParamSet.Rows[index].Cells[0].Value);
                prm.VelH = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[3].Value);
                prm.AccH = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[4].Value);
                prm.DccH = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[5].Value);

                prm.VelL = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[6].Value);
                prm.AccL = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[7].Value);
                prm.DccL = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[8].Value);
                prm.PlusePerRote = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[9].Value);
                prm.AxisLeadRange = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[10].Value);
                prm.d_SommothTime = Convert.ToDouble(dataGridView_AxisParamSet.Rows[index].Cells[11].Value);

                MotionMgr.GetInstace().SetAxisMoveParam(nAxisNo, prm);
                MotionMgr.GetInstace().SetAxisName(nAxisNo, dataGridView_AxisParamSet.Rows[index].Cells[1].Value == null ? "NoNamedAxis" : dataGridView_AxisParamSet.Rows[index].Cells[1].Value.ToString());
                string strAxisType = dataGridView_AxisParamSet.Rows[index].Cells[2].Value == null ? MotorType.SEVER.ToString() : dataGridView_AxisParamSet.Rows[index].Cells[2].Value.ToString();
                MotionMgr.GetInstace().SetMotorType(nAxisNo, (MotorType)Enum.Parse(typeof(MotorType), strAxisType));

                indexCell = 2;
                homePrm._nHomeMode = Convert.ToInt32(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm._bHomeDir = Convert.ToBoolean(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.VelH = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.AccH = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.DccH = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.VelL = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.AccL = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm.DccL = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                homePrm._iSeachOffstPluse = Convert.ToDouble(dataGridView_HomeSet.Rows[index].Cells[indexCell++].Value);
                MotionMgr.GetInstace().SetAxisHomeParam(nAxisNo, homePrm);
            }
            ConfigToolMgr.GetInstance().SaveMoveParam();
            ConfigToolMgr.GetInstance().SaveHomeParam();
            MotionIoLib.MotionMgr.GetInstace().d_Radio = (double)TB_RunRadio.Value / 100.0;
            ConfigToolMgr.GetInstance().SaveRunRadio();
            UIMessageBox.ShowSuccess("保存成功！");
        }

        public void UpdataMotonType()
        {
            DataGridViewComboBoxColumn dataColumnCollection = (DataGridViewComboBoxColumn)dataGridView_AxisParamSet.Columns[2];
            dataColumnCollection.Items.Clear();
            Array strItems = Enum.GetValues(typeof(MotorType));
            foreach (var temp in strItems)
            {
                dataColumnCollection.Items.Add(temp.ToString());
            }
        }
        void updatadataGridView()
        {
            dataGridView_AxisParamSet.Rows.Clear();
            UpdataMotonType();
            dataGridView_HomeSet.Rows.Clear();
            List<MotionCardBase> list = MotionMgr.GetInstace().GetCardList();
            TB_RunRadio.Value = (int)(MotionIoLib.MotionMgr.GetInstace().d_Radio * 100.0);
            TMovePrm movePrm = new TMovePrm();
            THomePrm homePrm = new THomePrm();
            foreach (var temp in list)
            {
                for (int index = temp.GetMinAxisNo(); index <= temp.GetMaxAxisNo(); index++)
                {
                    movePrm = MotionMgr.GetInstace().GetAxisMovePrm(index);
                    dataGridView_AxisParamSet.Rows.Add(index.ToString(),
                        MotionMgr.GetInstace().GetAxisName(index),
                        MotionMgr.GetInstace().GetMotorType(index).ToString(),
                        movePrm.VelH.ToString(), movePrm.AccH.ToString(), movePrm.DccH.ToString(),
                        movePrm.VelL.ToString(), movePrm.AccL.ToString(), movePrm.DccL.ToString(),
                        movePrm.PlusePerRote.ToString(), movePrm.AxisLeadRange.ToString(), movePrm.d_SommothTime.ToString());
                    homePrm = MotionMgr.GetInstace().GetAxisHomePrm(index);
                    dataGridView_HomeSet.Rows.Add(
                        index.ToString(),
                        MotionMgr.GetInstace().GetAxisName(index),
                        homePrm._nHomeMode.ToString(),
                        homePrm._bHomeDir.ToString(),
                        homePrm.VelH.ToString(), homePrm.AccH.ToString(), homePrm.DccH.ToString(),
                        homePrm.VelL.ToString(), homePrm.AccL.ToString(), homePrm.DccL.ToString(),
                        homePrm._iSeachOffstPluse.ToString());
                }
            }
            for (int i = 0; i < dataGridView_AxisParamSet.Columns.Count; i++)
            {
                dataGridView_AxisParamSet.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dataGridView_AxisParamSet.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            for (int i = 0; i < dataGridView_HomeSet.Columns.Count; i++)
            {
                dataGridView_HomeSet.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                dataGridView_HomeSet.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            dataGridView_AxisParamSet.DefaultCellStyle.ForeColor = Color.Black;
            dataGridView_HomeSet.DefaultCellStyle.ForeColor = Color.Black;
        }

        void ParamSave()
        {
            List<MotionCardBase> list = MotionMgr.GetInstace().GetCardList();
            TMovePrm movePrm = new TMovePrm();
            foreach (var temp in list)
            {
                for (int index = temp.GetMinAxisNo(); index <= temp.GetMaxAxisNo(); index++)
                {
                    movePrm = MotionMgr.GetInstace().GetAxisMovePrm(index);
                    MotionMgr.GetInstace().SetAxisMoveParam(index, movePrm);
                }
            }
            ConfigToolMgr.GetInstance().SaveMoveParam();
        }

        private void Form_AxisTestSunny_Load(object sender, EventArgs e)
        {
            sys.g_eventRightChanged += ChangedUserRight;
            GlobalVariable.g_eventStationStateChanged += GlobalVariable_g_eventStationStateChanged;
            GlobalVariable.g_eventControlModeChanged += GlobalVariable_g_eventControlModeChanged;

            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);

            dataGridView_AxisParamSet.Location = new Point(0, 0);
            updatadataGridView();

            dataGridView_AxisParamSet.ReadOnly = true;
            dataGridView_HomeSet.ReadOnly = true;
        }
        private void GlobalVariable_g_eventControlModeChanged(ControlMode currRunMode)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        public void ChangedUserRight(User CurrentUser)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        private void GlobalVariable_g_eventStationStateChanged(StationState currState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => GlobalVariable_g_eventStationStateChanged(currState)));
            else
            {
                if ((int)sys.g_User._userRight >= (int)UserRight.Debug && GlobalVariable.g_StationState != StationState.StationStateRun)
                {
                    this.Enabled = true;
                }
                else
                {
                    this.Enabled = false;
                }
            }
        }

        private void Btn_TestStop_Click(object sender, EventArgs e)
        {
            bExit = true;
        }

        bool bExit = false;
        private void Test_Click(object sender, EventArgs e)
        {
            if (GlobalVariable.g_StationState != StationState.StationStateStop)
            {
                UIMessageBox.Show("非手动状态，不允许执行测试");
                return;
            }
            if (!UIMessageBox.ShowAsk("是否执行测试？"))
            {
                return;
            }
            int nAxisNo = textBox_AxisNo.Text.ToInt();
            double dLen = textBox_MoveDistance.Text.ToDouble();
            int nCount = textBox_Count.Text.ToInt();
            int speedSel = 0;
            SpeedType speedType = SpeedType.Low;
            if (radioButton_HighSpeed.Checked)
            {
                speedType = SpeedType.High;
                speedSel = 1;
            }

            if (radioButton_LowSpeed.Checked)
            {
                speedSel = 3;
                speedType = SpeedType.Low;
            }
            if (speedSel == 0)
                return;

            BtnXDLaserTest.Enabled = false;
            Test.Enabled = false;
            bExit = false;
            Thread r = new Thread(() =>
            {
                try
                {
                    for (int i = 0; i < nCount; i++)
                    {
                        if (bExit)
                            break;
                        double d_NowPos = MotionMgr.GetInstace().GetAxisActPos(nAxisNo);
                        AxisMove(nAxisNo, d_NowPos + dLen, (int)speedType);
                        Thread.Sleep(textBox_InPosDelay.Text.ToInt());
                        d_NowPos = MotionMgr.GetInstace().GetAxisActPos(nAxisNo);
                        AxisMove(nAxisNo, d_NowPos - dLen, (int)speedType);
                        Thread.Sleep(textBox_InPosDelay.Text.ToInt());
                    }
                }
                catch (Exception ex)
                {
                    MotionMgr.GetInstace().StopAxis(nAxisNo);
                    UIMessageBox.ShowError(ex.Message);
                    return;
                }

                finally
                {
                    BeginInvoke(new Action(() =>
                    {
                        BtnXDLaserTest.Enabled = true;
                        Test.Enabled = true;
                    }));
                }
            });
            r.SetApartmentState(ApartmentState.STA);
            r.Start();
        }
        public void AxisMove(int nAxisNo, double distance, int speedtype)
        {
            string strError = "";
            MotionMgr.GetInstace().AbsMove(nAxisNo, distance, speedtype, ref strError);
            DoWhile doWhile = new DoWhile((time, dowhile, bmanual2) =>
            {
                AxisState axisState = MotionMgr.GetInstace().IsAxisNormalStop(nAxisNo);
                if (axisState == AxisState.NormalStop)
                    return WaranResult.Run;
                else if (axisState == AxisState.Moving)
                    return WaranResult.CheckAgain;
                else
                {
                    throw new Exception("电机测试报警停止" + string.Format("{0}轴状态:{1}", nAxisNo, axisState));
                }
            }, 3000000);
            if (doWhile.doSomething(doWhile, true) == WaranResult.Run)
                return;
            else
                throw new Exception("电机测试异常停止" + string.Format("轴{0}", nAxisNo));
        }
        private void BtnXDLaserTest_Click(object sender, EventArgs e)
        {
            if (GlobalVariable.g_StationState != StationState.StationStateStop)
            {
                UIMessageBox.Show("非手动状态，不允许执行测试");
                return;
            }
            if (!UIMessageBox.ShowAsk("是否执行测试？"))
            {
                return;
            }
            double dEndPos = txtEndPos.Text.ToDouble();
            double dStartPos = txtStartPos.Text.ToDouble();
            double nStepDistace = Math.Abs(txtStepDistance.Text.ToDouble());
            int nSteps = (int)(Math.Abs((dEndPos - dStartPos) / nStepDistace));
            nStepDistace = dEndPos > dStartPos ? nStepDistace : -nStepDistace;
            double dRlsDistance = Math.Abs(txtRlsDistance.Text.ToDouble());
            int nAxisNo = textBox_AxisNo.Text.ToInt();
            double dLen = textBox_MoveDistance.Text.ToDouble();
            int nCount = textBox_Count.Text.ToInt();
            int speedSel = 0;
            SpeedType speedType = SpeedType.Low;
            if (radioButton_HighSpeed.Checked)
            {
                speedType = SpeedType.High;
                speedSel = 1;
            }
            if (radioButton_LowSpeed.Checked)
            {
                speedSel = 3;
                speedType = SpeedType.Low;
            }
            if (speedSel == 0)
                return;
            dRlsDistance = dEndPos > dStartPos ? dRlsDistance : -dRlsDistance;
            int nSleep = textBox_InPosDelay.Text.ToInt();
            BtnXDLaserTest.Enabled = false;
            Test.Enabled = false;
            bExit = false;
            Thread r = new Thread(() =>
            {
                try
                {
                    for (int i = 0; i < nCount; i++)
                    {

                        for (int n = 0; n <= nSteps; n++)
                        {
                            if (bExit)
                                break;
                            AxisMove(nAxisNo, dStartPos + nStepDistace * n, (int)speedType);
                            Thread.Sleep(nSleep);
                        }

                        AxisMove(nAxisNo, dEndPos + dRlsDistance, (int)speedType);
                        Thread.Sleep(1000);

                        for (int n = 0; n <= nSteps; n++)
                        {
                            if (bExit)
                                break;
                            AxisMove(nAxisNo, dEndPos - nStepDistace * n, (int)speedType);
                            Thread.Sleep(nSleep);
                        }
                        AxisMove(nAxisNo, dStartPos - dRlsDistance, (int)speedType);
                        Thread.Sleep(1000);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"{Name} {ex.Message}\n{ex.StackTrace}");
                    MotionMgr.GetInstace().StopAxis(nAxisNo);
                    UIMessageBox.ShowError(ex.Message + "\r\n" + ex.StackTrace);
                    return;
                }
                finally
                {
                    BeginInvoke(new Action(() =>
                    {
                        BtnXDLaserTest.Enabled = true;
                        Test.Enabled = true;
                    }));
                }
            });
            r.SetApartmentState(ApartmentState.STA);
            r.Start();
        }
        private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strPassWord = "";
            if (UIInputDialog.InputPasswordDialog(this, ref strPassWord))
            {
                //if (strPassWord == "Huaya")
                {
                    dataGridView_AxisParamSet.ReadOnly = false;
                    dataGridView_HomeSet.ReadOnly = false;
                }
            }
        }
        private void 只读ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView_AxisParamSet.ReadOnly = true;
            dataGridView_HomeSet.ReadOnly = true;
        }
        private void TB_RunRadio_ValueChanged(object sender, EventArgs e)
        {
            lbl_RunRadio.Text = $"当前速度：{TB_RunRadio.Value}%";
        }
        private void ButtonColor(UIButton uIButton, Color color)
        {
            if (color == Color.Red)
            {
                uIButton.FillColor = Color.Red;
                uIButton.FillHoverColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(128)))));
                uIButton.FillPressColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
                uIButton.FillSelectedColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))));
            }
        }
    }
}
